ALTER PROCEDURE [dbo].[SP_FILL_DB_FIELDS] (@DEBUG int = 0)	
AS
BEGIN

declare @T_NAME varchar(100)
declare @F_NAME varchar(100)
declare @IND int
declare @IND1 int

create table #TEMPTABLE
( 
 T_NAME varchar(100),
 F_NAME varchar(100),
 D_TEXT varchar(100),
 ISID smallint,
 ISVISIBLE smallint,
 ISCOMBO smallint,
 IND int,
 ISREADONLY int,
 ISFILEUPLOAD int
)

declare CRTEMP cursor for
select t.name, c.name from dbo.sysobjects t 
inner join dbo.syscolumns c on t.id=c.id
where t.type='U' and c.name not in (select DF_FIELDNAME from DB_FIELDS) and
t.name<>'sysdiagrams'

open CRTEMP
fetch next from CRTEMP into @T_NAME, @F_NAME

while @@FETCH_STATUS = 0
begin

select @IND=isnull(max(DF_INDEX),0) from DB_FIELDS where DF_TABLENAME=@T_NAME
select @IND1=isnull(max(IND),0) from #TEMPTABLE where T_NAME=@T_NAME

if @IND1>=@IND
begin
 set @IND=@IND1
end

set @IND=@IND+1

insert into #TEMPTABLE 
 (T_NAME, F_NAME, D_TEXT, ISID, ISVISIBLE, ISCOMBO, IND, ISREADONLY, ISFILEUPLOAD) 
 values
 (@T_NAME, @F_NAME, @F_NAME, 0, 1, 0, @IND, 0, 0)

fetch next from CRTEMP into @T_NAME, @F_NAME
end

close CRTEMP
deallocate CRTEMP

update #TEMPTABLE set ISVISIBLE=0, ISID=1 where right(F_NAME,2)='ID'

update #TEMPTABLE set ISVISIBLE=0 where 
 right(F_NAME,11)='_CREATED_BY' or
 right(F_NAME,12)='_MODIFIED_BY' or
 right(F_NAME,9)='_MODIFIED' or 
 right(F_NAME,8)='_CREATED'

if @DEBUG=0
begin
 insert into DB_FIELDS (DF_TABLENAME,DF_FIELDNAME,DF_DISPLAYTEXT,DF_ISID,DF_ISVISIBLE,DF_ISCOMBO,DF_INDEX,DF_ISREADONLY)
 select * from #TEMPTABLE
end


select * from #TEMPTABLE

END
